(function (moduleName4Html, global, factory) {
    if (typeof module !== 'undefined' && typeof exports === 'object') {//CommonJS(NodeJS)
        module.exports = factory(global);
    } else if (typeof define === 'function' && (define.amd || define.cmd)) {//AMD   CMD
        define(function () { factory(global); });
    } else {//ES(Browser)
        global[moduleName4Html] = factory(global);
    }
}("knowledgeGraph", this, function (global) {
    'use strict';

    var knowledgeGraph = {
        graph: function (dataDetail, elementId) {
            var myChart = echarts.init(document.getElementById(elementId));
            //记录所有节点
            var allArr = [];
            //记录需要显示的节点
            var display = [];
            //节点的分类数据
            var categories = [];
            //图例显示数据
            var lengend = [];
            //相似文献
            var similiar = ["知网资源"];
            //是否有自用库权限
            var isAuthorized = "";
            //访问镜像资源的数据库
            var remoteDbCode = "";
            //查找最新成果时用到的数据库
            var newCGDbcode = "";
            //一般用到的数据库
            var dbCode = "";
            //文章核心
            var center = {};
            //文章列表
            var articleList = [];
            //相似文献数据库代码
            var tableCode = [];

            //判断是否有自用库权限
            shared.ajaxGet(config.showSelfBaseButton, {}, function callback(res) {
                isAuthorized = res;
            }, { async: false });

            //改变中心点显示
            center = { overallID: "", code: "", category: "本文", name: "本文", source: "本文", target: "本文", level: 1 };
            allArr.push(center);
            categories.push({ name: center.category });
            articleList.push(dataDetail.title);

            //该方法可展示文章详情
            function getGraphDetail(code, param, id, allArr) {
                if ("" !== param) {
                    for (var index = 0; index < param.length; index++) {
                        var obj = {};
                        if ("" !== code) {
                            obj = { overallID: "", code: code[index - 1], category: id, name: param[index], source: id, target: param[index], level: 3 };
                        } else {
                            obj = { overallID: "", code: "", category: id, name: param[index], source: id, target: param[index], level: 3 };
                        }
                        allArr.push(obj);
                    }
                }
            }

            //改变关键词显示
            var param = dataDetail.keyWord;
            if ("" !== param) {
                var paramList = param.split(";");
                for (var index = 0; index < paramList.length; index++) {
                    var obj = { overallID: "", code: "", category: "关键词", name: paramList[index], source: "关键词", target: paramList[index], level: 3 };
                    allArr.push(obj);
                }
            }

            //改变相似文献节点
            // var dbCodeNum = 0;

            // if (!isAuthorized) {//当不具有自用库权限
            //     dbCodeNum = 2;
            // } else {
            //     dbCodeNum = 3;
            // }
            // for (var i = 0; i < config.json.db.length; i++) {
            //     if (i < dbCodeNum) {
            //         similiar.push(config.json.db[i].showName);
            //         tableCode.push(config.json.db[i].dbCode);
            //         newCGDbcode += config.json.db[i].dbCode + ",";
            //         dbCode += config.json.db[i].dbCode + ",";
            //     } else if (i > dbCodeNum) {
            //         remoteDbCode += config.json.db[i].dbCode + ",";
            //         dbCode += config.json.db[i].dbCode + ",";
            //     }
            // }

            for (var i = 0; i < config.json.db.length; i++) {
                var element = config.json.db[i];
                var isBelongLocal = element.dataPermissionTree;//true属于本地(包括QBZS,CG,ZY,ZTWX)
                var isOpen = element.isOpen;//是否展示可见
                var isBelongSearch = element.getSimilarLiterature;//true属于可以查找的总范围;(包括QBZS,CG,ZY,ZTWX以及镜像库)
                if (isBelongSearch && !isBelongLocal) {//只包含镜像库的数据库代码
                    remoteDbCode += element.dbCode + ",";
                    dbCode += element.dbCode + ",";
                }
                if (isBelongLocal) {//只包含本地，并且验证了自用库权限的数据库代码
                    if (!isOpen && !isAuthorized) {
                       continue;
                    } else {
                        similiar.push(element.showName);
                        tableCode.push(element.dbCode);
                        newCGDbcode += element.dbCode + ",";
                        dbCode += element.dbCode + ",";
                    }
                }
            }
            getGraphDetail(tableCode, similiar, "相似文献", allArr);

            //读取配置文件，扩充领域子节点
            for (var a = 0; a < config.json.domain.length; a++) {
                var area = config.json.domain[a];
                if ((area.dbCode !== "QT") && (area.dbCode === dataDetail.area)) {
                    var organ = area.organ;
                    var technology = area.technology;
                    var specialist = area.specialist;
                    getGraphDetail("", specialist, "专家学者", allArr);
                    getGraphDetail("", technology, "核心技术", allArr);
                    getGraphDetail("", organ, "权威机构", allArr);
                    break;
                }
            }

            //读取配置文件，完成基础设定
            for (var b = 0; b < config.json.knowledgeGraph.length; b++) {
                var obj1 = config.json.knowledgeGraph[b];
                var newObj = { overallID: "", code: "", category: obj1.category, name: obj1.target, source: obj1.source, target: obj1.target, level: obj1.target };
                if (newObj.source === "本文") {
                    if ((newObj.category === "领域")) {
                        if (dataDetail.area !== "QT") {
                            newObj.category = dataDetail.field + "领域";
                            newObj.target = dataDetail.field + "领域";
                            newObj.name = dataDetail.field + "领域";
                        } else {
                            newObj.code = "QT"
                        }

                    }
                    newObj.level = 2;
                } else {
                    if (newObj.source === "领域") {
                        if (dataDetail.area !== "QT") {
                            newObj.source = dataDetail.field + "领域";
                        } else {
                            newObj.code = "QT"
                        }
                    }
                    newObj.level = 3;
                }
                //不放入展示的领域
                if (newObj.code !== "QT") {
                    allArr.push(newObj);
                    lengend.push({ name: newObj.category });
                    categories.push({ name: newObj.category });
                }
                //用最新成果放入展示
                if (newObj.code === "QT" && newObj.name === "最新成果") {
                    newObj.source = "本文";
                    allArr.push(newObj);
                    lengend.push({ name: newObj.category });
                    categories.push({ name: newObj.category });
                }
            }
            display = allArr;
            getGraph(display, categories);

            function getGraph(data, categories) {
                //生成节点所需的数据对象
                var data1 = data.map(function (node) {
                    return {
                        code: node.code,
                        overallID: node.overallID,
                        source: node.source,
                        target: node.target,
                        name: node.name,
                        level: node.level,
                        category: node.category,
                        symbolSize: (5 - node.level) * 22,//支持度越大，节点越大
                        label: {
                            normal: {
                                fontSize: node.level === 4 ? 14 : (10 - node.level) * 2,
                                position: node.level === 4 ? 'bottom' : 'inside',
                            }
                        }
                    };
                });

                //生成连线所需的数据对象
                var link1 = data.map(function (node) {
                    return {
                        source: node.source,
                        target: node.target,
                        level: node.level,
                        label: {
                            normal: {
                                show: false,
                                formatter: function () {
                                    return node.name;
                                }
                            }
                        },
                        lineStyle: {
                            normal: {
                                width: 0.4 * (10 - node.level),//连线粗细
                                color: 'target'
                            }
                        }
                    };
                });

                //指定配置项和数据
                var option = {
                    legend: {
                        x: 'left',//图例居中
                        padding: [10, 0, 0, 30],   //可设定图例[距上方距离，距右方距离，距下方距离，距左方距离]
                        top: 20,
                        orient: 'vertical',
                        textStyle: { //图例文字的样式
                            // color: '#fff',
                            fontSize: 14
                        },
                        selectedMode: false,//取消图例上的点击事件
                        data: lengend,
                    },
                    tooltip: { // 提示框
                        formatter: function (x) {
                            return x.data.name;
                        }
                    },
                    series: [{
                        type: 'graph', // 类型:关系图
                        layout: 'force', //图的布局，类型为力导图
                        data: data1,
                        links: link1,
                        categories: categories,
                        draggable: true,
                        roam: true, // 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移,可以设置成 'scale' 或者 'move'。设置成 true 为都开启
                        focusNodeAdjacency: true,   // 是否在鼠标移到节点上的时候突出显示节点以及节点的边和邻接节点。[ default: false ]
                        itemStyle: {
                            normal: {
                                // borderColor: '#fff',
                                // borderWidth: 1,
                                shadowBlur: 10,
                            }
                        },
                        label: {
                            normal: {
                                show: true,
                                fontFamily: "Microsoft YaHei",
                                formatter: function (param) {
                                    var name = param.name;
                                    if (name.length > 10) {
                                        name = name.slice(0, 10) + '...';
                                    }
                                    return name;
                                },
                            }
                        },
                        edgeSymbol: ['none', 'arrow'],
                        force: {
                            repulsion: 200,
                            gravity: 0.1,
                            edgeLength: 80,
                        },
                        lineStyle: {
                            normal: {
                                show: true,
                                opacity: 0.9,
                                curveness: 0,//边的曲度，支持从 0 到 1 的值，值越大曲度越大。
                            }
                        },
                    }]
                };
                myChart.setOption(option);
            }
            //递归查找所有子节点
            var newArray = [];
            function getchild(display, source) {
                for (var i = 0; i < display.length; i++) {
                    if (display[i].source === source && display[i].target !== source) {
                        newArray.push(display[i]);
                        getchild(display, display[i].target);
                    }
                }
            }

            //查找文章详情
            function getArticleDetail(sysID, url) {
                shared.ajaxPost(url, { sysID: sysID }, function (res) {
                    console.log(res,777)
                    res.dbTable = res.tableName;
                    pageData.toDetail(res);
                });
            }

            // 下面为点击某个节点之后进行的操作，其实就是像display加入要显示的子节点.节点的显示和隐藏只是改变节点data数组即可，link始终不需要改变。
            myChart.on('click', function (params) {
                //当点击的节点不是文章
                if ("" === params.data.overallID) {
                    //本次点击需要添加或删除的节点
                    var addArr = [];
                    //记录本次点击需要添加的元素的子元素是否已经在display数组中，如果在，说明本次点击需要从display中删除掉addArr中节点；不在，需要添加到待显示数组display中
                    var exist = false;
                    //递归查找当前节点所有子节点
                    getchild(display, params.data.target);
                    for (var x = 0; x < display.length; x++) {
                        if ((display[x].source === params.data.target) && (display[x].target !== display[x].source)) {
                            exist = true;
                            break;
                        }
                    }
                    if (exist) {//元素的子元素已经在display数组中，需删除子元素
                        for (var y = 0; y < display.length; y++) {
                            var isDelete = true;
                            for (var z = 0; z < newArray.length; z++) {
                                if (display[y] === newArray[z]) {
                                    isDelete = false;
                                    break;
                                }
                            }
                            if (isDelete) {
                                addArr.push(display[y]);
                            }
                        }
                        display = addArr;
                        newArray = [];
                        getGraph(display, categories);
                    } else {//元素的子元素不在display数组中，需增加子元素
                        var beforeLength = display.length;
                        for (var r = 0; r < allArr.length; r++) {
                            if (allArr[r].source === params.data.target) {
                                if (allArr[r].source !== allArr[r].target) {
                                    display.push(allArr[r]);
                                    categories.push(allArr[r].category);
                                }
                            }
                        }

                        //当增加的节点是文章
                        if (beforeLength === display.length) {
                            if (params.data.source !== "相似文献") {
                                var keyWord = "";
                                var dbCodeList = "";
                                if (params.data.target === "最新成果") {
                                    dbCodeList = newCGDbcode.substring(0, newCGDbcode.lastIndexOf(','));
                                    keyWord = "领域 = " + dataDetail.area;
                                } else {
                                    switch (params.data.source) {
                                        case '专家学者':
                                            keyWord = "作者 % '*" + params.data.name + "'";
                                            break;
                                        case '权威机构':
                                            keyWord = "机构 % '*" + params.data.name + "'";
                                            break;
                                        case '核心技术':
                                            keyWord = "主题 % '" + params.data.name + "'";
                                            break;
                                        case '关键词':
                                            keyWord = "关键词 % '*" + params.data.name + "'";
                                            break;
                                        default:
                                            break;
                                    }
                                    dbCodeList = dbCode.substring(0, dbCode.lastIndexOf(','));
                                }
                            } else {
                                if (params.data.name === "知网资源") {
                                    keyWord = "(SYS_VSM = '" + dataDetail.vsm + "'" + " OR SYS_VSM_EN = '" + dataDetail.vsmen + "')";
                                    dbCodeList = remoteDbCode.substring(0, remoteDbCode.lastIndexOf(','));
                                } else {
                                    keyWord = "(SYS_VSM = '" + dataDetail.vsm + "'" + " OR SYS_VSM_EN = '" + dataDetail.vsmen + "')";
                                    dbCodeList = params.data.code;
                                }
                            }

                            shared.ajaxGet('/knowledge/ralatedArticlesList', { dbCodeList: dbCodeList, keyWord: keyWord }, function (res) {
                                if ("" !== res) {
                                    var articleLength = articleList.length;
                                    for (var index = 0; index < res.length; index++) {
                                        var flag = true;
                                        for (var k = 0; k < articleList.length; k++) {
                                            if (res[index].title === articleList[k]) {
                                                flag = false;
                                                break;
                                            }
                                        }
                                        if (flag) {
                                            var target = res[index].tableName + "+" + res[index].fileName;
                                            if (res[index].tableName === "JZQBZS_METADATA" || res[index].tableName === "JZCG_METADATA" || res[index].tableName === "JZZY_METADATA" || res[index].tableName === "JZZTWX_METADATA") {
                                                target = res[index].tableName + "+" + res[index].sysID;
                                            }
                                            var obj = { overallID: target, category: params.data.category, name: res[index].title, source: params.data.target, target: res[index].title, level: 4 };
                                            display.push(obj);
                                            articleList.push(res[index].title);
                                        }
                                    }
                                    if (articleLength === articleList.length) {
                                        // layer.msg(params.data.source + ":" + params.data.name + "下相似文章已展示，或当前分类下无相似文章");
                                        layer.msg("暂无资源！");
                                    } else {
                                        getGraph(display, categories);
                                    }
                                } else {
                                    layer.msg("暂无资源！");
                                }
                            });
                        } else {
                            getGraph(display, categories);
                        }
                    }
                } else {
                    var overallID = params.data.overallID.split("+"),
                        type = overallID[0];
                    if (type === "JZQBZS_METADATA") {
                        getArticleDetail(overallID[1], config.getKnowledgeDetail);
                    } else if (type === "JZCG_METADATA" || type === "JZZY_METADATA") {
                        getArticleDetail(overallID[1], config.getResultDetail);
                    }else if (type === "JZZTWX_METADATA") {
                        getArticleDetail(overallID[1], config.getWxtDetail);
                    } else {
                        var loadUrl = config.getOutResourceDetail.replace('{0}', type);
                        var toUrl = loadUrl.replace('{1}', overallID[1])
                        window.open(toUrl)
                    }
                }
            });
        }
    };
    return knowledgeGraph;
}));
